<template>
  <div class="data-tools">
    <ToolContainer
      tool-name="数据分析"
      default-tab="visualization"
      @tab-change="handleTabChange"
    >
      <template #tabs>
        <!-- 数据可视化标签页 -->
        <el-tab-pane label="数据可视化" name="visualization">
          <ToolSection
            show-upload
            upload-text="拖拽数据文件到此处或点击上传"
            upload-tip="支持CSV、XLSX、JSON格式"
            :upload-icon="UploadFilled"
            accept=".csv,.xlsx,.json"
            :multiple="true"
            :show-file-list="true"
            @file-change="handleFileChange"
          >
            <template #preview>
              <div v-if="dataFiles.length" class="file-list">
                <div v-for="file in dataFiles" :key="file.uid" class="file-info">
                  <p><strong>文件名：</strong>{{ file.name }}</p>
                  <p><strong>大小：</strong>{{ file.sizeText }}</p>
                </div>
              </div>
            </template>

            <template #options>
              <div v-if="dataFiles.length" class="visualization-options">
                <el-form label-width="100px">
                  <el-form-item label="图表类型">
                    <el-select v-model="chartType" placeholder="选择图表类型">
                      <el-option label="折线图" value="line" />
                      <el-option label="柱状图" value="bar" />
                      <el-option label="饼图" value="pie" />
                      <el-option label="散点图" value="scatter" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleVisualize" 
                :loading="loading"
                :disabled="dataFiles.length === 0"
              >
                批量生成图表
              </el-button>
              <el-button 
                type="success" 
                @click="handleBatchDownloadCharts" 
                :loading="loading"
                :disabled="chartImages.length === 0"
              >
                批量下载图表
              </el-button>
            </template>

            <template #result>
              <div v-if="chartImages.length" class="chart-list">
                <div v-for="(img, idx) in chartImages" :key="idx" class="chart-item">
                  <img :src="img" alt="chart" style="max-width: 100%; max-height: 200px;" />
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>
        
        <!-- 统计分析标签页 -->
        <el-tab-pane label="统计分析" name="analysis">
          <ToolSection
            show-upload
            upload-text="拖拽数据文件到此处或点击上传"
            upload-tip="支持CSV、XLSX、JSON格式"
            :upload-icon="UploadFilled"
            accept=".csv,.xlsx,.json"
            @file-change="handleFileChange"
          >
            <template #preview>
              <div v-if="fileName" class="file-preview">
                <div class="file-info">
                  <p><strong>文件名：</strong>{{ fileName }}</p>
                  <p><strong>文件大小：</strong>{{ fileSize }}</p>
                </div>
              </div>
            </template>

            <template #options>
              <div v-if="fileName" class="analysis-options">
                <el-form label-width="100px">
                  <el-form-item label="分析类型">
                    <el-select v-model="analysisType" placeholder="选择分析类型">
                      <el-option label="描述性统计" value="descriptive" />
                      <el-option label="相关性分析" value="correlation" />
                      <el-option label="回归分析" value="regression" />
                      <el-option label="时间序列分析" value="timeseries" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="分析字段">
                    <el-select
                      v-model="selectedFields"
                      multiple
                      placeholder="选择分析字段"
                    >
                      <el-option
                        v-for="field in dataFields"
                        :key="field"
                        :label="field"
                        :value="field"
                      />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleAnalyze" 
                :loading="loading"
                :disabled="!fileName || selectedFields.length === 0"
              >
                开始分析
              </el-button>
              <el-button 
                type="success" 
                @click="handleExport" 
                :loading="loading"
                :disabled="!analysisResults"
              >
                导出报告
              </el-button>
            </template>

            <template #result>
              <div v-if="analysisResults" class="analysis-results">
                <h4>分析结果：</h4>
                <pre>{{ JSON.stringify(analysisResults, null, 2) }}</pre>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>
        
        <!-- 数据转换标签页 -->
        <el-tab-pane label="数据转换" name="transform">
          <ToolSection
            show-upload
            upload-text="拖拽数据文件到此处或点击上传"
            upload-tip="支持CSV、XLSX、JSON格式"
            :upload-icon="UploadFilled"
            accept=".csv,.xlsx,.json"
            @file-change="handleFileChange"
          >
            <template #preview>
              <div v-if="fileName" class="file-preview">
                <div class="file-info">
                  <p><strong>文件名：</strong>{{ fileName }}</p>
                  <p><strong>文件大小：</strong>{{ fileSize }}</p>
                </div>
              </div>
            </template>

            <template #options>
              <div v-if="fileName" class="transform-options">
                <el-form label-width="100px">
                  <el-form-item label="转换类型">
                    <el-select v-model="transformType" placeholder="选择转换类型">
                      <el-option label="数据透视表" value="pivot" />
                      <el-option label="数据分组" value="group" />
                      <el-option label="数据合并" value="merge" />
                      <el-option label="数据筛选" value="filter" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="转换字段">
                    <el-select
                      v-model="transformFields"
                      multiple
                      placeholder="选择转换字段"
                    >
                      <el-option
                        v-for="field in dataFields"
                        :key="field"
                        :label="field"
                        :value="field"
                      />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleTransform" 
                :loading="loading"
                :disabled="!fileName || transformFields.length === 0"
              >
                开始转换
              </el-button>
              <el-button 
                type="success" 
                @click="handleDownload" 
                :loading="loading"
                :disabled="!transformResults"
              >
                下载结果
              </el-button>
            </template>

            <template #result>
              <div v-if="transformResults" class="transform-results">
                <h4>转换结果：</h4>
                <pre>{{ JSON.stringify(transformResults, null, 2) }}</pre>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>
      </template>
    </ToolContainer>

    <!-- 功能介绍组件 -->
    <FeatureIntro
      :title="featureConfig.title"
      :description="featureConfig.description"
      :header-icon="featureConfig.headerIcon"
      :features="featureConfig.features"
      :initial-visible="showIntro"
      @close="showIntro = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import ToolContainer from '@/components/ToolContainer.vue'
import ToolSection from '@/components/ToolSection.vue'
import FeatureIntro from '@/components/FeatureIntro.vue'
import { featuresConfig } from '@/config/featuresConfig.js'

interface DataFile {
  uid: string
  name: string
  size: number
  sizeText: string
  raw: File
  content?: string
}

const loading = ref(false)
const showIntro = ref(true)
const featureConfig = featuresConfig.dataTools

// 数据文件相关
const dataFiles = ref<DataFile[]>([])
const chartType = ref('line')
const chartImages = ref<string[]>([])
const fileName = ref('')
const fileSize = ref('')
const dataFields = ref([])

// 分析相关
const analysisType = ref('descriptive')
const selectedFields = ref([])
const analysisResults = ref(null)

// 转换相关
const transformType = ref('pivot')
const transformFields = ref([])
const transformResults = ref(null)

function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

function handleTabChange(tabName: string) {
  console.log('切换到标签页:', tabName)
}

function handleFileChange(file: any, fileList: any[]) {
  dataFiles.value = []
  fileList.forEach(async (item) => {
    const fileData: DataFile = {
      uid: item.uid,
      name: item.name,
      size: item.size,
      sizeText: formatFileSize(item.size),
      raw: item.raw
    }
    
    // 读取文件内容
    try {
      const content = await readFileContent(item.raw)
      fileData.content = content
      
      // 解析数据字段
      if (item.raw.name.endsWith('.csv')) {
        const fields = parseCSVFields(content)
        dataFields.value = fields
      } else if (item.raw.name.endsWith('.json')) {
        const fields = parseJSONFields(content)
        dataFields.value = fields
      }
      
      fileName.value = item.name
      fileSize.value = formatFileSize(item.size)
    } catch (error) {
      ElMessage.error('文件读取失败：' + error.message)
    }
    
    dataFiles.value.push(fileData)
  })
}

// 读取文件内容
function readFileContent(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => resolve(e.target?.result as string)
    reader.onerror = () => reject(new Error('文件读取失败'))
    reader.readAsText(file)
  })
}

// 解析CSV字段
function parseCSVFields(content: string): string[] {
  const lines = content.split('\n')
  if (lines.length > 0) {
    return lines[0].split(',').map(field => field.trim().replace(/"/g, ''))
  }
  return []
}

// 解析JSON字段
function parseJSONFields(content: string): string[] {
  try {
    const data = JSON.parse(content)
    if (Array.isArray(data) && data.length > 0) {
      return Object.keys(data[0])
    } else if (typeof data === 'object') {
      return Object.keys(data)
    }
  } catch (error) {
    console.error('JSON解析失败:', error)
  }
  return []
}

async function handleVisualize() {
  if (!dataFiles.value.length) {
    ElMessage.warning('请先上传数据文件')
    return
  }
  loading.value = true
  
  try {
    const charts = []
    for (const file of dataFiles.value) {
      if (file.content) {
        const chartImage = await generateChart(file.content, file.name, chartType.value)
        charts.push(chartImage)
      }
    }
    chartImages.value = charts
    loading.value = false
    ElMessage.success('图表生成完成')
  } catch (error) {
    loading.value = false
    ElMessage.error('图表生成失败：' + error.message)
  }
}

// 生成图表
async function generateChart(content: string, filename: string, type: string): Promise<string> {
  return new Promise((resolve) => {
    const canvas = document.createElement('canvas')
    canvas.width = 400
    canvas.height = 300
    const ctx = canvas.getContext('2d')!
    
    // 绘制背景
    ctx.fillStyle = '#ffffff'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    
    // 绘制标题
    ctx.fillStyle = '#333333'
    ctx.font = '16px Arial'
    ctx.textAlign = 'center'
    ctx.fillText(`${filename} - ${type}图表`, canvas.width / 2, 30)
    
    // 根据图表类型绘制不同的图形
    switch (type) {
      case 'line':
        drawLineChart(ctx, canvas.width, canvas.height)
        break
      case 'bar':
        drawBarChart(ctx, canvas.width, canvas.height)
        break
      case 'pie':
        drawPieChart(ctx, canvas.width, canvas.height)
        break
      case 'scatter':
        drawScatterChart(ctx, canvas.width, canvas.height)
        break
    }
    
    resolve(canvas.toDataURL())
  })
}

// 绘制折线图
function drawLineChart(ctx: CanvasRenderingContext2D, width: number, height: number) {
  const data = [20, 45, 30, 60, 40, 80, 55]
  const padding = 50
  const chartWidth = width - 2 * padding
  const chartHeight = height - 2 * padding - 50
  
  ctx.strokeStyle = '#409EFF'
  ctx.lineWidth = 2
  ctx.beginPath()
  
  data.forEach((value, index) => {
    const x = padding + (index / (data.length - 1)) * chartWidth
    const y = padding + 50 + (1 - value / 100) * chartHeight
    
    if (index === 0) {
      ctx.moveTo(x, y)
    } else {
      ctx.lineTo(x, y)
    }
    
    // 绘制数据点
    ctx.fillStyle = '#409EFF'
    ctx.beginPath()
    ctx.arc(x, y, 3, 0, 2 * Math.PI)
    ctx.fill()
  })
  
  ctx.stroke()
}

// 绘制柱状图
function drawBarChart(ctx: CanvasRenderingContext2D, width: number, height: number) {
  const data = [30, 60, 45, 80, 35, 70]
  const padding = 50
  const chartWidth = width - 2 * padding
  const chartHeight = height - 2 * padding - 50
  const barWidth = chartWidth / data.length * 0.8
  
  ctx.fillStyle = '#67C23A'
  
  data.forEach((value, index) => {
    const x = padding + (index + 0.1) * (chartWidth / data.length)
    const barHeight = (value / 100) * chartHeight
    const y = padding + 50 + chartHeight - barHeight
    
    ctx.fillRect(x, y, barWidth, barHeight)
  })
}

// 绘制饼图
function drawPieChart(ctx: CanvasRenderingContext2D, width: number, height: number) {
  const data = [30, 25, 20, 15, 10]
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  const centerX = width / 2
  const centerY = height / 2 + 25
  const radius = Math.min(width, height) / 4
  
  let currentAngle = 0
  
  data.forEach((value, index) => {
    const sliceAngle = (value / 100) * 2 * Math.PI
    
    ctx.fillStyle = colors[index % colors.length]
    ctx.beginPath()
    ctx.moveTo(centerX, centerY)
    ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle)
    ctx.closePath()
    ctx.fill()
    
    currentAngle += sliceAngle
  })
}

// 绘制散点图
function drawScatterChart(ctx: CanvasRenderingContext2D, width: number, height: number) {
  const padding = 50
  const chartWidth = width - 2 * padding
  const chartHeight = height - 2 * padding - 50
  
  ctx.fillStyle = '#E6A23C'
  
  // 生成随机散点数据
  for (let i = 0; i < 50; i++) {
    const x = padding + Math.random() * chartWidth
    const y = padding + 50 + Math.random() * chartHeight
    
    ctx.beginPath()
    ctx.arc(x, y, 2, 0, 2 * Math.PI)
    ctx.fill()
  }
}

const handleAnalyze = async () => {
  if (!fileName.value) {
    ElMessage.warning('请先上传数据文件')
    return
  }
  if (selectedFields.value.length === 0) {
    ElMessage.warning('请选择分析字段')
    return
  }
  loading.value = true
  
  try {
    const file = dataFiles.value[0]
    if (file.content) {
      const results = await performDataAnalysis(file.content, analysisType.value, selectedFields.value)
      analysisResults.value = results
      loading.value = false
      ElMessage.success('分析完成')
    }
  } catch (error) {
    loading.value = false
    ElMessage.error('分析失败：' + error.message)
  }
}

// 执行数据分析
async function performDataAnalysis(content: string, type: string, fields: string[]): Promise<any> {
  const data = parseDataContent(content)
  
  switch (type) {
    case 'descriptive':
      return calculateDescriptiveStats(data, fields)
    case 'correlation':
      return calculateCorrelation(data, fields)
    case 'regression':
      return performRegression(data, fields)
    case 'timeseries':
      return analyzeTimeSeries(data, fields)
    default:
      throw new Error('不支持的分析类型')
  }
}

// 解析数据内容
function parseDataContent(content: string): any[] {
  try {
    // 尝试解析为JSON
    return JSON.parse(content)
  } catch {
    // 解析为CSV
    const lines = content.split('\n')
    const headers = lines[0].split(',').map(h => h.trim().replace(/"/g, ''))
    const data = []
    
    for (let i = 1; i < lines.length; i++) {
      if (lines[i].trim()) {
        const values = lines[i].split(',').map(v => v.trim().replace(/"/g, ''))
        const row: any = {}
        headers.forEach((header, index) => {
          row[header] = isNaN(Number(values[index])) ? values[index] : Number(values[index])
        })
        data.push(row)
      }
    }
    
    return data
  }
}

// 计算描述性统计
function calculateDescriptiveStats(data: any[], fields: string[]): any {
  const stats: any = {}
  
  fields.forEach(field => {
    const values = data.map(row => row[field]).filter(v => typeof v === 'number')
    if (values.length > 0) {
      stats[field] = {
        count: values.length,
        mean: values.reduce((a, b) => a + b, 0) / values.length,
        min: Math.min(...values),
        max: Math.max(...values),
        median: calculateMedian(values),
        stdDev: calculateStdDev(values)
      }
    }
  })
  
  return stats
}

// 计算中位数
function calculateMedian(values: number[]): number {
  const sorted = [...values].sort((a, b) => a - b)
  const mid = Math.floor(sorted.length / 2)
  return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]
}

// 计算标准差
function calculateStdDev(values: number[]): number {
  const mean = values.reduce((a, b) => a + b, 0) / values.length
  const variance = values.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / values.length
  return Math.sqrt(variance)
}

// 计算相关性
function calculateCorrelation(data: any[], fields: string[]): any {
  const correlations: any = {}
  
  for (let i = 0; i < fields.length; i++) {
    for (let j = i + 1; j < fields.length; j++) {
      const field1 = fields[i]
      const field2 = fields[j]
      const values1 = data.map(row => row[field1]).filter(v => typeof v === 'number')
      const values2 = data.map(row => row[field2]).filter(v => typeof v === 'number')
      
      if (values1.length > 0 && values2.length > 0) {
        correlations[`${field1}_${field2}`] = calculatePearsonCorrelation(values1, values2)
      }
    }
  }
  
  return correlations
}

// 计算皮尔逊相关系数
function calculatePearsonCorrelation(x: number[], y: number[]): number {
  const n = Math.min(x.length, y.length)
  const sumX = x.slice(0, n).reduce((a, b) => a + b, 0)
  const sumY = y.slice(0, n).reduce((a, b) => a + b, 0)
  const sumXY = x.slice(0, n).reduce((sum, xi, i) => sum + xi * y[i], 0)
  const sumX2 = x.slice(0, n).reduce((sum, xi) => sum + xi * xi, 0)
  const sumY2 = y.slice(0, n).reduce((sum, yi) => sum + yi * yi, 0)
  
  const numerator = n * sumXY - sumX * sumY
  const denominator = Math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY))
  
  return denominator === 0 ? 0 : numerator / denominator
}

// 执行回归分析
function performRegression(data: any[], fields: string[]): any {
  if (fields.length < 2) {
    throw new Error('回归分析至少需要两个字段')
  }
  
  const xField = fields[0]
  const yField = fields[1]
  const xValues = data.map(row => row[xField]).filter(v => typeof v === 'number')
  const yValues = data.map(row => row[yField]).filter(v => typeof v === 'number')
  
  const n = Math.min(xValues.length, yValues.length)
  const sumX = xValues.slice(0, n).reduce((a, b) => a + b, 0)
  const sumY = yValues.slice(0, n).reduce((a, b) => a + b, 0)
  const sumXY = xValues.slice(0, n).reduce((sum, xi, i) => sum + xi * yValues[i], 0)
  const sumX2 = xValues.slice(0, n).reduce((sum, xi) => sum + xi * xi, 0)
  
  const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX)
  const intercept = (sumY - slope * sumX) / n
  const rSquared = Math.pow(calculatePearsonCorrelation(xValues, yValues), 2)
  
  return {
    equation: `y = ${slope.toFixed(4)}x + ${intercept.toFixed(4)}`,
    slope,
    intercept,
    rSquared,
    xField,
    yField
  }
}

// 时间序列分析
function analyzeTimeSeries(data: any[], fields: string[]): any {
  // 简化的时间序列分析
  const timeField = fields.find(f => f.toLowerCase().includes('time') || f.toLowerCase().includes('date'))
  const valueField = fields.find(f => f !== timeField)
  
  if (!timeField || !valueField) {
    throw new Error('时间序列分析需要时间字段和数值字段')
  }
  
  const values = data.map(row => row[valueField]).filter(v => typeof v === 'number')
  const trend = calculateTrend(values)
  const seasonality = calculateSeasonality(values)
  
  return {
    timeField,
    valueField,
    trend,
    seasonality,
    mean: values.reduce((a, b) => a + b, 0) / values.length,
    volatility: calculateStdDev(values)
  }
}

// 计算趋势
function calculateTrend(values: number[]): string {
  if (values.length < 2) return 'insufficient data'
  
  const firstHalf = values.slice(0, Math.floor(values.length / 2))
  const secondHalf = values.slice(Math.floor(values.length / 2))
  
  const firstMean = firstHalf.reduce((a, b) => a + b, 0) / firstHalf.length
  const secondMean = secondHalf.reduce((a, b) => a + b, 0) / secondHalf.length
  
  if (secondMean > firstMean * 1.05) return 'upward'
  if (secondMean < firstMean * 0.95) return 'downward'
  return 'stable'
}

// 计算季节性
function calculateSeasonality(values: number[]): number {
  // 简化的季节性检测
  const periods = [4, 7, 12] // 季度、周、月
  let maxCorrelation = 0
  
  periods.forEach(period => {
    if (values.length > period * 2) {
      const correlation = calculateAutocorrelation(values, period)
      maxCorrelation = Math.max(maxCorrelation, Math.abs(correlation))
    }
  })
  
  return maxCorrelation
}

// 计算自相关
function calculateAutocorrelation(values: number[], lag: number): number {
  const n = values.length - lag
  const mean = values.reduce((a, b) => a + b, 0) / values.length
  
  let numerator = 0
  let denominator = 0
  
  for (let i = 0; i < n; i++) {
    numerator += (values[i] - mean) * (values[i + lag] - mean)
  }
  
  for (let i = 0; i < values.length; i++) {
    denominator += Math.pow(values[i] - mean, 2)
  }
  
  return denominator === 0 ? 0 : numerator / denominator
}

const handleTransform = async () => {
  if (!fileName.value) {
    ElMessage.warning('请先上传数据文件')
    return
  }
  if (transformFields.value.length === 0) {
    ElMessage.warning('请选择转换字段')
    return
  }
  loading.value = true
  
  try {
    const file = dataFiles.value[0]
    if (file.content) {
      const results = await performDataTransform(file.content, transformType.value, transformFields.value)
      transformResults.value = results
      loading.value = false
      ElMessage.success('转换完成')
    }
  } catch (error) {
    loading.value = false
    ElMessage.error('转换失败：' + error.message)
  }
}

// 执行数据转换
async function performDataTransform(content: string, type: string, fields: string[]): Promise<any> {
  const data = parseDataContent(content)
  
  switch (type) {
    case 'pivot':
      return createPivotTable(data, fields)
    case 'group':
      return groupData(data, fields)
    case 'merge':
      return mergeData(data, fields)
    case 'filter':
      return filterData(data, fields)
    default:
      throw new Error('不支持的转换类型')
  }
}

// 创建数据透视表
function createPivotTable(data: any[], fields: string[]): any {
  if (fields.length < 2) {
    throw new Error('透视表至少需要两个字段')
  }
  
  const rowField = fields[0]
  const valueField = fields[1]
  const pivot: any = {}
  
  data.forEach(row => {
    const key = row[rowField]
    if (!pivot[key]) {
      pivot[key] = []
    }
    pivot[key].push(row[valueField])
  })
  
  // 计算统计信息
  Object.keys(pivot).forEach(key => {
    const values = pivot[key].filter((v: any) => typeof v === 'number')
    pivot[key] = {
      count: values.length,
      sum: values.reduce((a: number, b: number) => a + b, 0),
      average: values.length > 0 ? values.reduce((a: number, b: number) => a + b, 0) / values.length : 0
    }
  })
  
  return pivot
}

// 数据分组
function groupData(data: any[], fields: string[]): any {
  const groupField = fields[0]
  const groups: any = {}
  
  data.forEach(row => {
    const key = row[groupField]
    if (!groups[key]) {
      groups[key] = []
    }
    groups[key].push(row)
  })
  
  return groups
}

// 数据合并
function mergeData(data: any[], fields: string[]): any {
  // 简化的合并操作：按指定字段去重
  const mergeField = fields[0]
  const merged: any[] = []
  const seen = new Set()
  
  data.forEach(row => {
    const key = row[mergeField]
    if (!seen.has(key)) {
      seen.add(key)
      merged.push(row)
    }
  })
  
  return merged
}

// 数据筛选
function filterData(data: any[], fields: string[]): any {
  // 简化的筛选：只保留指定字段不为空的记录
  return data.filter(row => {
    return fields.every(field => row[field] !== null && row[field] !== undefined && row[field] !== '')
  })
}

const handleDownload = () => {
  if (!transformResults.value) {
    ElMessage.warning('请先进行数据转换')
    return
  }
  
  const blob = new Blob([JSON.stringify(transformResults.value, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'transform_results.json'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('下载成功')
}

const handleExport = () => {
  if (!analysisResults.value) {
    ElMessage.warning('请先进行数据分析')
    return
  }
  
  const blob = new Blob([JSON.stringify(analysisResults.value, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'analysis_report.json'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('导出成功')
}

async function handleBatchDownloadCharts() {
  if (!chartImages.value.length) {
    ElMessage.warning('请先生成图表')
    return
  }
  loading.value = true
  chartImages.value.forEach((img, idx) => {
    downloadImage(img, `chart_${idx + 1}.png`)
  })
  loading.value = false
  ElMessage.success('批量下载图表完成')
}

function downloadImage(url: string, filename: string) {
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}
</script>

<style scoped>
.data-tools {
  min-height: 100vh;
  width: 100vw;
  background: none;
  margin: 0;
  padding: 0;
}

.el-main {
  padding: 20px 40px;
  background-color: #f5f7fa;
}

.tool-container {
  max-width: 800px;
  margin: 0 auto;
}

.tool-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.upload-area {
  width: 100%;
}

.file-info {
  text-align: center;
  color: #606266;
}

.visualization-options,
.analysis-options,
.transform-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.button-group {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.chart-container,
.analysis-results,
.transform-results {
  width: 100%;
  min-height: 400px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
}

.file-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin: 20px 0;
}

.chart-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin: 20px 0;
}

.chart-item {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 8px;
}

@media (max-width: 768px) {
  .button-group {
    flex-direction: column;
  }
  
  .el-button {
    width: 100%;
  }
}
</style> 